﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AnsQ.infoViewModel;
using AnsQ.Models;
using System.Data;

namespace AnsQ.App_Start
{
    public class MyAuthorizeAttribute: AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (HttpContext.Current.Request.RequestType == "OPTIONS")
            {
                filterContext.HttpContext.Response.StatusCode = 200;
            }
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (HttpContext.Current.Request.RequestType == "OPTIONS")
            {
                //httpContext.Response.StatusCode = 200;
                httpContext.Response.StatusCode = 200;
                return true;
            }

            var authHeader = httpContext.Request.Headers["auth"];

            if (authHeader == null || authHeader == "undefined")
            {
                httpContext.Response.StatusCode = 403;
                return false;
            }
            var userinfo = JWT.JwtHelp.GetJwtDecode(authHeader);
            UserTokenViewModel userTokenView = GetUserTokenViewModel(userinfo.PlayName);
            if (userTokenView.ID== userinfo.ID)
            {
                return true;
            }
            httpContext.Response.StatusCode = 403;
            return false;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);
            if (filterContext.HttpContext.Response.StatusCode == 403)
            {
                filterContext.Result = new RedirectResult("/Error");
                filterContext.HttpContext.Response.Redirect("/Home/Error");
            }
        }

        public UserTokenViewModel GetUserTokenViewModel(string username)
        {
            UserTokenViewModel userTokenViewModel = new UserTokenViewModel();
           DataTable table= Helper.TSQLHelper.GetDataTableBySQL("select [Guid] from TokenList,AUser where AUser.ID=TokenList.UID and PlayName=@pname", new string[] { "@pname" },new string[] { username });
            foreach (DataRow row in table.Rows)
            {
                userTokenViewModel.ID = row["Guid"].ToString();
            }
            return userTokenViewModel;
        }
    }
}